package czk.concrent.producerAndConsumer.practice;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.LinkedList;

/**
 * 消息队列的模拟
 * @Author:ChenZhangKun
 * @Date: 2020/11/5 22:55
 */
public class MessageQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        MessageQueue messageQueue=new MessageQueue(5);
        for (int i = 0; i < 10; i++) {
            Message message=new Message(i,"czk");
            new Thread(()->{
                try {
                    messageQueue.put(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        Thread.sleep(5000);
        while (true){
            Thread.sleep(1000);
            new Thread(()->{
                Message message = messageQueue.get();
                System.out.println(message);
            }).start();
        }
    }

}
class MessageQueue{
    private Integer capCity;
    private LinkedList<Message> list=new LinkedList<>();
    public MessageQueue(Integer capCity) {
        this.capCity = capCity;
    }
    public boolean isFull(){
        return list.size()>=capCity;
    }
    public boolean isEmpty(){
        return list.size()==0;
    }
    public Message get(){
        synchronized (list){
            while (list.isEmpty()){
                System.out.println("没有消息，等待着");
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 通知其他线程添加
            list.notifyAll();
            // 有消息了
            Message message = list.removeFirst();
            return message;
        }

    }
    public void put(Message message) throws InterruptedException {
        synchronized (list){
            while (list.size()==capCity){
                System.out.println("队列满了，需要等待");
                list.wait();
            }
            // 添加
            list.addLast(message);
            list.notifyAll();
        }
    }
}
@Data
@AllArgsConstructor
class Message{
    private Integer id;
    private String name;

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

